package com.gxa.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxa.auth.OAuth2Token;
import com.gxa.common.exception.RRException;
import com.gxa.common.utils.CommonUtils;
import com.gxa.common.utils.MD5Util;
import com.gxa.common.utils.ShiroUtils;
import com.gxa.dto.userdto.MenuDto;
import com.gxa.entity.user.SysMenu;
import com.gxa.entity.user.SysRole;
import com.gxa.entity.user.SysUser;
import com.gxa.mapper.user.SysMenuMapper;
import com.gxa.mapper.user.SysRoleMapper;
import com.gxa.service.user.SysMenuService;
import com.gxa.service.user.SysUserService;
import com.gxa.mapper.user.SysUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.*;
import java.util.List;

/**
* @author Administrator
* @description 针对表【sys_user(用户表)】的数据库操作Service实现
* @createDate 2022-10-16 21:06:08
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService{
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private SysMenuService sysMenuService;
    @Override
    public SysUser queryByUserName(String username) {

        return sysUserMapper.selectUserByUsername(username);
    }

    @Override
    public SysUser queryById(Integer id) {
        return sysUserMapper.selectUserById(id);
    }

    /**
     * 根据token 获取设置用户信息
     * @param jwtToken
     * @param user
     * @return
     */
    @Override
    public Map<String, Object> getUserWithToken(OAuth2Token jwtToken, SysUser user) {
        user.setPassword(null);//去除敏感信息
        //1- 封装token
        Map<String,Object> userInfoMap = new HashMap<>();
        userInfoMap.put("token",jwtToken.getToken());
        userInfoMap.put("expireTime",jwtToken.getExipreAt());
        // 2- 得到用户角色
        List<SysRole> roles = this.roleMapper.selectRoleListByUsername(user.getUsername());
        //3.  得到用户菜单 菜单中有权限
//        List<SysMenu> userMenus = this.sysMenuService.getUserMenu(user.getUsername());
        List<MenuDto> userMenus = this.sysMenuService.mygetUserMenu(user.getUsername());
        List<SysMenu> userMenu = this.sysMenuService.getUserMenu(user.getUsername());//用户的菜单 有perms

        Set<String> perms = new HashSet<>();//当前用户权限
        for(SysMenu menu:userMenu){
            String perm = menu.getPermission();
            perms.add(perm);
        }

        userInfoMap.put("perms",perms);
        userInfoMap.put("roles",roles);
        userInfoMap.put("user",user);
        userInfoMap.put("userMenus",userMenus);//菜单树


        return userInfoMap;
    }

    @Override
    public IPage<SysUser> selectUserList(Integer currentPage, Integer pageSize, String nickname) {
        IPage<SysUser> userPage = null;
        try {
            Page<SysUser> page = new Page<>(currentPage,pageSize);
            // 用户分页
            userPage = this.sysUserMapper.selectUserList(page, nickname);
            // 加入用户对应角色
            for (SysUser user: userPage.getRecords()) {
                List<SysRole> roleList = this.roleMapper.selectRoleListByUsername(user.getUsername());
                if(null != roleList && roleList.size() > 0){
                    user.setRoles(roleList);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RRException("查询用户列表失败");
        }
        return userPage;
    }

    @Override
    public void saveUserRoles(String[] roleIds, String userId) {
        // 1 删除用户原有的角色
        this.sysUserMapper.deleteUserRoles(userId);
        // 2 保存用户跟新的角色
        this.sysUserMapper.insertUserRoles(roleIds,userId);
    }

    @Override
    public boolean saveOrUpdateUser(SysUser user) {
        boolean flag;
        // 当前用户
        SysUser currentUser = this.getCurrentUser();
        // 新增
        if(StringUtils.isBlank(user.getId())){
            user.setStatus("0");
            String id = CommonUtils.getUUID();
            user.setId(id);
            String password = MD5Util.encrypt(user.getUsername(), "password");
            user.setPassword(password);
            this.createEntity(user,currentUser);
            this.updateEntity(user,currentUser);
            //新增时授予游客角色
            this.sysUserMapper.insertTouristsRole(id);
            this.sysUserMapper.insert(user);
            flag = true;
        }else{
            //修改
            this.updateEntity(user,currentUser);
            this.sysUserMapper.updateById(user);
            flag =false;
        }
        return flag;
    }


    public void updateEntity(SysUser user,SysUser currentUser) {
        if (null != user) {
            user.setUpdator(currentUser.getId());
            user.setUpdatorName(currentUser.getUsername());
        }
        user.setUpdateTime(new Date());
    }

    public void createEntity(SysUser user,SysUser currentUser) {
        if (null != user) {
            user.setCreator(currentUser.getId());
            user.setCreatorName(currentUser.getUsername());
        }
        user.setCreateTime(new Date());
    }

    @Override
    public SysUser getCurrentUser() {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        String username = ShiroUtils.getUsername();
        return this.sysUserMapper.selectOne(queryWrapper.eq("USERNAME",username));
    }

    @Override
    public List<SysUser> findRoleWithUser(String id) {
        try {
            return this.baseMapper.findRoleWithUser(id);
        }catch (Exception e){
            throw new RRException("查找当前角色所属用户失败");
        }
    }
}




